package com.sy.simpleegg.upgrade;

import android.util.Base64;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 文件下载管理器，包括管理url参数、下载APK包、获取任务字符串。<br/>
 *
 * @author Sodino E-mail:sodinoopen@hotmail.com
 * @version Time：2011-4-6 下午03:42:50
 */
public class FileDownloader {

    public interface OnDownloadListener {
        void onDownloadSuccess(String loadUrl, String filePath);

        void onDownloading(long progress, long total);

        void onDownloadFailed(String errorInfo);
    }

    public static void download(final String savePath, final String name, final String url, final OnDownloadListener listener) {
        long startPosition = 0;
        final File dir = new File(savePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(savePath, name);
        if (file.exists()){
            startPosition = file.length();
            Log.d("download", "startPosition = " + startPosition);
        }
        final long contentSize = getContentSize(savePath.substring(savePath.lastIndexOf("/") + 1));
        Request request;
            request = new Request.Builder()
                    .addHeader("Accept-Encoding","identity")
                    .addHeader("RANGE","bytes=" + startPosition + "-")
                    .url(url)
                    .build();

        Call call = new OkHttpClient().newCall(request);
        final long finalStartPosition = startPosition;
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                if (listener != null) listener.onDownloadFailed(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                FileOutputStream fos = null;
                File file = new File(dir, name);
                // 储存下载文件的目录
//                String savePath = Constants.APK_PATH;
//                File file = new File(savePath, getNameFromUrl(url));
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();// 剩余下载量
                    saveContentSize(savePath.substring(savePath.lastIndexOf("/") + 1), total, contentSize);
                    Log.d("FileDownloader", "total = " + total);
                    if (name.endsWith(".txt")){
                        if (file.exists()) {
                            file.delete();
                        }
                    }else if (name.endsWith(".apk")){
                        if (file.exists() && file.length() >= contentSize) {
                            if (listener != null) listener.onDownloadSuccess(url, file.getPath());
                            return;
                        }
                    }
                    fos = new FileOutputStream(file, true);
                    long sum = finalStartPosition;
//                    long sum = 0;
                    int len = 0;
                    RandomAccessFile raf = new RandomAccessFile(file, "rw");
                    while ((len = is.read(buf)) != -1){
                        raf.seek(sum);
                        raf.write(buf,0,len);
                        sum += len;
                        Log.d("FileDownloader", "sum = " + sum);

//                        if (listener != null) listener.onDownloading(sum, contentSize); // 下载中
                        if (listener != null) listener.onDownloading(sum, total); // 下载中
                    }
                    Log.d("FileDownloader", "write finish");
//                    while ((len = is.read(buf)) != -1) {
//                        fos.write(buf, 0, len);
//                        sum += len;
//                        Log.d("FileDownloader", "sum = " + sum);
//                        if (listener != null) listener.onDownloading(sum, total); // 下载中
//                    }
                    fos.flush();
                    if (listener != null) listener.onDownloadSuccess(url, file.getPath());  // 下载完成
                } catch (Exception e) {
//                    file.delete();
                    if (listener != null) listener.onDownloadFailed(e.getMessage());
                    //LogUtil.d("downManager"+e.toString());
                } finally {
                    try {
                        if (is != null) is.close();
                    } catch (Exception e) {
                    }
                    try {
                        if (fos != null) fos.close();
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
        Log.e("DownloadDialog", "Base64解码前:" + fileName);
        try {
            String aa = new String(Base64.decode(fileName, Base64.DEFAULT));
//            LogUtil.d("DownloadDialog" + "Base64解码后:" + aa);
        } catch (Exception e) {
//            LogUtil.d("DownloadDialog" + "Base64解码异常:" + e.getMessage());
        }
        fileName += System.currentTimeMillis() + url.substring(url.lastIndexOf("."));
        return fileName;
    }

    public static void saveContentSize(String version, long size, long contentSize){
//        SPUtils spUtil = SPUtils.getInstance("config");
//        long s = spUtil.getLong(version);
//        if (s < 0){
//            spUtil.put(version, size);
//            contentSize = size;
//        }
    }

    public static long getContentSize(String version){
//        SPUtils spUtil = SPUtils.getInstance("config");
//        return spUtil.getLong(version);
        return 0;
    }

}